package com.ggh.jinjilive.ui.live;

import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.dyhdyh.support.countdowntimer.CountDownTimerSupport;
import com.dyhdyh.support.countdowntimer.OnCountDownTimerListener;
import com.ggh.jinjilive.BaseApplication;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.common.MerchantSession;
import com.ggh.jinjilive.databinding.ActivityTvLiveBinding;
import com.ggh.jinjilive.dialog.LiveOccludeDialog;
import com.ggh.jinjilive.dialog.LivePromptDialog;
import com.ggh.jinjilive.dialog.LiveSendMessageDialog;
import com.ggh.jinjilive.dialog.LiveShrinkageDialog;
import com.ggh.jinjilive.dialog.OnlineDialog;
import com.ggh.jinjilive.listener.AddItemOnClickListener;
import com.ggh.jinjilive.listener.AddOnClickListener;
import com.ggh.jinjilive.listener.AddOnClickListener1;
import com.ggh.jinjilive.mobile.create.StartLiveMobile;
import com.ggh.jinjilive.mobile.live.LiveMessageMobile;
import com.ggh.jinjilive.mobile.live.SellGoodsMobile;
import com.ggh.jinjilive.mobile.live.ShrinkageMobile;
import com.ggh.jinjilive.mobile.live.im.CustomMessage;
import com.ggh.jinjilive.mobile.live.im.MessageEntity;
import com.ggh.jinjilive.mobile.live.im.MessageMobile;
import com.ggh.jinjilive.mobile.live.im.PKHomeowners;
import com.ggh.jinjilive.ui.BaseActivity;
import com.ggh.jinjilive.ui.live.adapter.SellGoodsAdapter;
import com.ggh.jinjilive.ui.live.adapter.TVLiveMessageAdapter;
import com.ggh.jinjilive.ui.live.adapter.TVLiveRoomPersonnelAdapter;
import com.ggh.jinjilive.utils.ARouterUtils;
import com.ggh.jinjilive.utils.TimeUtils;
import com.ggh.jinjilive.utils.im.LiveMessageUtils;
import com.ggh.jinjilive.utils.im.TCConstants;
import com.ggh.jinjilive.utils.loginIMUtils;
import com.ggh.jinjilive.views.faceunity.FURenderer;
import com.ggh.jinjilive.views.faceunity.IFURenderer;
import com.ggh.jinjilive.views.faceunity.utils.CameraUtils;
import com.ggh.jinjilive.views.live.barrage.TCDanmuMgr;
import com.ggh.jinjilive.views.live.gift.adapter.GiftBarAdapter;
import com.ggh.jinjilive.views.live.gift.bean.GiftDemoModel;
import com.ggh.jinjilive.views.live.gift.bean.UserDemoInfo;
import com.ggh.jinjilive.views.live.gift.interfacei.GiftModelI;
import com.ggh.jinjilive.views.live.gift.interfacei.UserInfoI;
import com.ggh.jinjilive.views.live.gift.periscope.GiftAnimLayout;
import com.ggh.jinjilive.views.live.model.CameraPush;
import com.ggh.jinjilive.views.live.model.CameraPushImpl;
import com.ggh.jinjilive.views.live.pk.commondef.AnchorInfo;
import com.ggh.jinjilive.views.live.pk.commondef.AudiencePKGiftStatistics;
import com.ggh.jinjilive.views.live.pk.commondef.PKProgress;
import com.ggh.jinjilive.views.live.pk.commondef.RoomInfo;
import com.ggh.jinjilive.views.live.pk.http.HttpRequests;
import com.ggh.jinjilive.views.live.pk.http.HttpResponse;
import com.ggh.jinjilive.views.live.pk.http.PKHttpRequests;
import com.ggh.jinjilive.views.live.pk.mobile.AnchorInfopk;
import com.ggh.jinjilive.views.live.redrain.RedPacketViewHelper;
import com.ggh.jinjilive.views.live.redrain.model.BoxInfo;
import com.ggh.jinjilive.views.live.redrain.model.BoxPrizeBean;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMGroupMemberInfoResult;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMValueCallback;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.TXLivePusher;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import pl.droidsonroids.gif.AnimationListener;
import pl.droidsonroids.gif.GifDrawable;


@Route(path = ARouterUtils.TVLiveActivity)
public class TVLiveActivity extends BaseActivity<ActivityTvLiveBinding> implements View.OnClickListener, CameraPush.OnLivePusherCallback,SensorEventListener{
    private TVLiveViewModel tvLiveViewModel;
    //传说过来的数据
    private StartLiveMobile startLiveMobile;

    //退出提示
    private LiveOccludeDialog liveOccludeDialog;
    //提示弹框
    private LivePromptDialog livePromptDialog;
    //在线主播
    private OnlineDialog onlineDialog;
    //直播收缩
    private LiveShrinkageDialog liveShrinkageDialog;
    //当前主播
    private CameraPush cameraPush;
    //PK
    private TXLivePlayer player;
    //美颜
    private FURenderer mFURenderer;
    //摄像头
    private int mCameraFacing = IFURenderer.CAMERA_FACING_FRONT;
    //前置还是后置摄像头
    private boolean mFrontCameraFlag = true;
    //闪光灯
    private boolean mIsTorchOpenFlag = false;
    //暂停直播
    private boolean pauseLive = true;
    //传感器
    private SensorManager mSensorManager;
    //设置开启或关闭观众端镜像
    private boolean audienceMirroring = true;
    //发送消息
    private LiveSendMessageDialog liveSendMessageDialog;
    //聊天适配器
    private TVLiveMessageAdapter tvLiveMessageAdapter;
    //SVG
    private SVGAParser mSVGAParser;
    //用户头像
    private TVLiveRoomPersonnelAdapter tvLiveRoomPersonnelAdapter;
    //直播间人数
    private int liveStudioNumber = 0;
    //弹幕弹框
    private TCDanmuMgr mDanmuMgr;
    //红包雨区分
    private int redRainDistinguish = 0;
    //gif提示
    private GifDrawable gifDrawablePrompt;
    private GifDrawable gifDrawable;
    //红包雨
    private RedPacketViewHelper mRedPacketViewHelper;

    //pk信息
    private AnchorInfopk mPKAnchorInfo = new AnchorInfopk();
    //当前是否在pk中
    private boolean isPk = false;
    // 格式化时间
    private SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private String pkStartTime = "";   //pk开始时间
    private PKProgress pkProgress = new PKProgress(); //PK进度条数据
    private LinkedList<AudiencePKGiftStatistics> pkContributionList = new LinkedList<>();  //单次PK中的观众礼物统计
    //总时长 间隔时间
    private CountDownTimerSupport countDownTimerSupport = new CountDownTimerSupport(1000 * 300, 1000);
    ///////////////////////////////////////////////////////////带货任务////////////////////////////////////////////////////////////////////////////
    //任务列表
    private RecyclerView sellGoods;
    private SellGoodsAdapter sellGoodsAdapter;
    @Override
    public void initCreate() {
        super.initCreate();
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        BaseApplication.getInstance().getAppComponent().doInjectionMain(this);
        tvLiveViewModel = new ViewModelProvider(this,viewModelFactory).get(TVLiveViewModel.class);

    }

    @Override
    public void initParam() {
        super.initParam();
        Intent intent = getIntent();
        startLiveMobile = (StartLiveMobile) intent.getSerializableExtra("startLiveMobile");
        if(null != tvLiveViewModel){
            tvLiveViewModel.startLiveMobileObservableField.set(startLiveMobile);
        }
    }
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_tv_live;

    }


    @Override
    public void initView() {
        super.initView();

        //在线主播
        onlineDialog = new OnlineDialog(mContext);
        //直播间信息
        tvLiveViewModel.anchorView(userMobile.getUser_id());
        //获取状态栏高度
        binding.llSpacing.setPadding(0, BarUtils.getStatusBarHeight(),0,0);
        //直播收缩
        liveShrinkageDialog = new LiveShrinkageDialog(mContext);
        //退出提示
        liveOccludeDialog = new LiveOccludeDialog(mContext);
        //提示弹框
        livePromptDialog = new LivePromptDialog(mContext);
        //发送消息
        liveSendMessageDialog = new LiveSendMessageDialog(this,R.style.DialogTheme);

        //美颜初始化
        FURenderer.setup(this);
        mFURenderer = new FURenderer
                .Builder(this)
                .setInputTextureType(FURenderer.INPUT_TEXTURE_2D)
                .setInputImageOrientation(CameraUtils.getCameraOrientation(mCameraFacing))
                .setRunBenchmark(true).build();
        binding.faceUnityView.setModuleManager(mFURenderer);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        //初始化SVG
        if (mSVGAParser == null) {
            mSVGAParser = SVGAParser.Companion.shareParser();
        }

        //直播初始化
        cameraPush = new CameraPushImpl(this, binding.pusherTxCloudView);
        //
        setVideoProcessListener(cameraPush.getTXLivePusher());
        //设置是否开启静音推流
        cameraPush.setMute(false);
        //设置开启或关闭观众端镜像
        cameraPush.setMirror(true);
        //设置开启或关闭水印
        cameraPush.setWatermark(false);
        //设置开启或关闭手动对焦
        cameraPush.setTouchFocus(false);
        //设置开启或关闭双手缩放
        cameraPush.setEnableZoom(false);
        //开启纯音频推流。
        cameraPush.enablePureAudioPush(false);
        //设置耳返开关
        cameraPush.enableAudioEarMonitoring(false);
        //设置视频编码质量
        cameraPush.setQuality(false,  TXLiveConstants.VIDEO_QUALITY_HIGH_DEFINITION);
        //设置音质选择（声道设置）
        cameraPush.setAudioQuality(1, 48000);
        //设置横竖屏推流
        cameraPush.setHomeOrientation(false);
        //设置开启或关闭后置摄像头闪光灯
        cameraPush.turnOnFlashLight(false);
        //设置硬件加速
        cameraPush.setHardwareAcceleration(false);
        //回调
        cameraPush.setOnLivePusherCallback(this);
        //设置地址
        cameraPush.setURL(startLiveMobile.getPush_url());
        // 进入页面，自动开始推流，并且弹出推流对应的拉流地址
        cameraPush.startPush();
        //控制台调整
        binding.liveMusicMixer.setAudioEffectManager(cameraPush.getTXLivePusher().getAudioEffectManager());
        //关闭控制台
        binding.liveMusicMixer.setAddOnClickListener(new AddOnClickListener() {
            @Override
            public void onSkipClicked(String sKip) {
                if(sKip.equals("关闭")){
                    binding.liveMusicMixer.setVisibility(View.GONE);
                }
            }
        });
        //聊天适配器
        tvLiveMessageAdapter = new TVLiveMessageAdapter(mContext);
        tvLiveMessageAdapter.setAddItemOnClickListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                if(position == 0){
                    String messageEntity = (String) mObject;
                    if(null != liveSendMessageDialog && !liveSendMessageDialog.isShowing()) {
                        liveSendMessageDialog.show();
                        liveSendMessageDialog.etContent("@" + messageEntity);
                        liveSendMessageDialog.setAddOnClickListener(new AddOnClickListener() {
                            @Override
                            public void onSkipClicked(String sKip) {
                                sendMessage(sKip);
                                liveSendMessageDialog.dismiss();
                            }
                        });
                    }
                }
            }
        });
        binding.tvMessageList.setLayoutManager(new LinearLayoutManager(mContext));
        binding.tvMessageList.setAdapter(tvLiveMessageAdapter);
        //更新直播间人数
        getGroupMemberList();
        //静态礼物特效
        binding.liveGift.setGiftAdapterAndCallBack(new GiftBarAdapter());//具体作用看GiftBarAdapter注释
        binding.liveGift.setMaxShowCount(4);
        //下面3个方法结合使用吧，我的能力有限。我不想搞这么麻烦的东西了，
        binding.liveGift.setMustAnimHide(true);
        binding.liveGift.setAllowAcrossAnimBug(false);
        binding.liveGift.setThanQueueClearFirstAndNotAddQueue(false);

        binding.liveGift.setAcrossDValue(1);
        binding.liveGift.setHidenAnim(R.anim.follow_anim_from_left_to_right_hidden);
        binding.liveGift.setShowDuration(4200);
        binding.liveGift.setKeyGenerationRuleHolder(new GiftAnimLayout.KeyGenerationRuleHolder() {
            @Override
            public String onRequestGenerationRule(GiftModelI modelI, UserInfoI userInfoI) {
//                return modelI.getGiftImage() + "" + userInfoI.getUserId() + "" + new Date().getTime() + "";//不再xxxxx 但是这样必须在holder里面隐藏它。
                return modelI.getGiftImage() + "" + userInfoI.getUserId();//不再xxxxx 但是这样必须在holder里面隐藏它。
            }
        });
        binding.liveGift.setThanMaxShowClearZero(true);
        //
        tvLiveRoomPersonnelAdapter = new TVLiveRoomPersonnelAdapter();
        //设置起始时间为当前时间
        binding.ChronometerTimer.setBase(SystemClock.elapsedRealtime());
        //设置显示格式
        binding.ChronometerTimer.setFormat("%s");
        //启动计时器
        binding.ChronometerTimer.start();
        // 实例化 弹幕
        mDanmuMgr = new TCDanmuMgr(mContext);
        mDanmuMgr.setDanmakuView(binding.mDanmuView);
        //红包雨
        mRedPacketViewHelper = new RedPacketViewHelper(this);
        mRedPacketViewHelper.setAddOnClickListener(new AddOnClickListener() {
            @Override
            public void onSkipClicked(String sKip) {
                if(sKip.equals("开启")){
                    if(redRainDistinguish == TCConstants.IMCMD_HBRain){
                        //领取直播间红包雨
                        tvLiveViewModel.getRedsrain();
                    }else if(redRainDistinguish == TCConstants.IMCMD_HBRain_ALL){
                        //领取平台红包雨
                        tvLiveViewModel.getRedsrains();
                    }
                }
            }
        });
        //带货控件
        ViewGroup.LayoutParams params = binding.navView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels / 2; //屏幕的三分之一
        binding.navView.setLayoutParams(params);
        View headView = binding.navView.getHeaderView(0);
        LinearLayout llsellgoods = headView.findViewById(R.id.ll_sell_goods);
        //带货控件状态栏高度
        llsellgoods.setPadding(0, BarUtils.getStatusBarHeight() + SizeUtils.dp2px(10),0,0);
        //任务列表
        sellGoods = headView.findViewById(R.id.rv_sellGoods);
        sellGoods.setLayoutManager(new LinearLayoutManager(mContext));
        sellGoodsAdapter = new SellGoodsAdapter();
        sellGoodsAdapter.setAddItemOnClickListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                SellGoodsMobile sellGoodsMobile = (SellGoodsMobile) mObject;
                if(null != sellGoodsMobile){
                    if(position == 0){//修改任务状态（是否带货中）
                        tvLiveViewModel.taskInfo(sellGoodsMobile);
                        loginIMUtils.finishSellGoods(tvLiveViewModel.liveMessageMobileMutableLiveData.getValue().getRoom_id());
                    }else if(position == 1){

                    }

                }
            }
        });
        sellGoods.setAdapter(sellGoodsAdapter);
    }





    @Override
    public void initData() {
        super.initData();
        //主播接的任务列表
        tvLiveViewModel.myTaskList();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //消息
        binding.imgLiveMessage.setOnClickListener(this);
        //连麦点击
        binding.llTvEvenMai.setOnClickListener(this);
        //关闭
        binding.imgLiveOcclude.setOnClickListener(this);
        //直播收缩
        binding.imgLiveShrinkage.setOnClickListener(this);
        //隐藏美颜
        binding.faceUnityView.setAddOnClickListener(new AddOnClickListener() {
            @Override
            public void onSkipClicked(String sKip) {
                if(sKip.equals("隐藏")){
                    binding.faceUnityView.setVisibility(View.GONE);
                }
            }
        });
        //直播间信息
        tvLiveViewModel.liveMessageMobileMutableLiveData.observe(this, new Observer<LiveMessageMobile>() {
            @Override
            public void onChanged(LiveMessageMobile liveMessageMobile) {
                //主播头像
                Glide.with(binding.rivHeadLike).load(liveMessageMobile.getHead_portrait()).into(binding.rivHeadLike);
                //主播名称
                binding.tvNickname.setText(liveMessageMobile.getNickname());
                //主播ID
                binding.tvAnchorId.setText("ID:"+liveMessageMobile.getAnchor_id());
                //钻石
                binding.tvLiveDiamond.setText(liveMessageMobile.getMy_silver_wallet() +"");
                //守护
                binding.tvLiveGuardian.setText("守护：" + liveMessageMobile.getGuard_num() + "人");
            }
        });

        //自定义消息回调
        loginIMUtils.addSimpleMsgListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                if(position == 0){//
                    String[] strings = (String[]) mObject;
                    if(strings.length > 0){
                        String adminUserName = strings[0];
                        String adminHead = strings[1];
                        String adminLevel = strings[2];
                        String adminGrand = strings[3];
                        String adminContent = strings[4];
                        String yellow = strings[5];
                        String level_img = strings[6];
                        CustomMessage customMessage = null;
                        if(yellow.equals("yellow")){
                            customMessage = new CustomMessage();
                            customMessage.cmd = "2";
                            MessageEntity messageEntity = new MessageEntity();
                            messageEntity.setRank(Integer.valueOf(adminLevel));
                            messageEntity.setNickname(adminUserName);
                            messageEntity.setLevel_img(level_img);
                            customMessage.msg = new Gson().toJson(messageEntity);
                            liveStudioNumber ++;
                            tvLiveViewModel.number.set(liveStudioNumber);
                            //更新直播间人数
                            tvLiveViewModel.realLiveUpdate();
                            binding.tvLiveNumber.setText(liveStudioNumber +"");
                        }else if(yellow.equals("white")){
                            customMessage = new CustomMessage();
                            customMessage.cmd = "1";
                            MessageEntity messageEntity = new MessageEntity();
                            messageEntity.setRank(Integer.valueOf(adminLevel));
                            messageEntity.setNickname(adminUserName);
                            messageEntity.setLevel_img(level_img);
                            messageEntity.setMessage(adminContent);
                            customMessage.msg = new Gson().toJson(messageEntity);
                        }
                        //数据添加
                        LiveMessageUtils.getInstance().robotMessage(customMessage,tvLiveMessageAdapter,binding.tvMessageList);
                    }
                }else if(position == 1){
                    CustomMessage customMessage = (CustomMessage) mObject;
                    if(null != customMessage && null != tvLiveMessageAdapter){
                        MessageEntity messageEntity = new Gson().fromJson(customMessage.msg, MessageEntity.class);
                        switch (customMessage.cmd){
//                            case "2"://进入房间的提示
//                                if(isPk){
//                                    //
//                                    AnchorInfopk anchorInfopk = new AnchorInfopk();
//                                    anchorInfopk.other_id_pk = mPKAnchorInfo.userID;
//                                    anchorInfopk.accelerateURL = mPKAnchorInfo.accelerateURL;
//                                    anchorInfopk.start_time_pk = pkStartTime;
//                                    MessageEntity pKmessageEntity = new MessageEntity();
//                                    pKmessageEntity.setMessage(new Gson().toJson(anchorInfopk));
//                                    pKmessageEntity.setNickname(MerchantSession.getInstance().getUser().getNickname());
//                                    pKmessageEntity.setRank(MerchantSession.getInstance().getUser().getLevel());
//                                    pKmessageEntity.setLevel_img(MerchantSession.getInstance().getUser().getLevel_img());
//                                    pKmessageEntity.setIs_guard("0");
//                                    //发送群PK消息
//                                    PksendGroup(String.valueOf(TCConstants.IMCMD_enter_pk),new Gson().toJson(pKmessageEntity));
//                                    //向刚进入房间的观众更新对方主播的礼物进度条
//                                    PksendGroup(String.valueOf(TCConstants.IMCMD_pk_gift_progress), new Gson().toJson(pkProgress));
//                                    //向刚进入房间的观众更新PK贡献表
//                                    pKmessageEntity = new MessageEntity();
//                                    pKmessageEntity.setMessage(new Gson().toJson(pkContributionList));
//                                    PksendGroup(String.valueOf(TCConstants.IMCMD_pk_contributionList), new Gson().toJson(pKmessageEntity));
//                                }
//                                break;
                            case "3":
                                liveStudioNumber --;
                                tvLiveViewModel.number.set(liveStudioNumber);
                                binding.tvLiveNumber.setText(liveStudioNumber +"");
                                //更新直播间人数
                                tvLiveViewModel.realLiveUpdate();
                                break;
                            case "5"://弹幕消息
                                if (mDanmuMgr != null) {
                                    mDanmuMgr.addDanmu(customMessage.userAvatar, customMessage.userName, messageEntity.getMessage());
                                }
                                break;
                            case "8"://直播礼物
                                MessageMobile messageMobile = new Gson().fromJson(messageEntity.getMessage(),MessageMobile.class);
                                UserDemoInfo info = new UserDemoInfo();
                                info.setName(messageMobile.getNickname());
                                info.setUserId(messageMobile.getUser_id() + "");
                                info.setGiftName("送一个"+ messageMobile.getName());
                                info.setPortraitUri(messageMobile.getHead_portrait());
                                GiftModelI model = new GiftDemoModel(messageMobile.getStatic_img_url());
                                binding.liveGift.showNewGift(mContext, info, model);
                                if(messageMobile.getIs_show() == 1){
                                    try { // new URL needs try catch.
                                        SVGAParser parser = SVGAParser.Companion.shareParser();
                                        parser.decodeFromURL(new URL(messageMobile.getDynamic_img_url()), new SVGAParser.ParseCompletion() {
                                            @Override
                                            public void onComplete(@NotNull SVGAVideoEntity videoItem) {
                                                SVGADrawable drawable = new SVGADrawable(videoItem);
                                                binding.liveSvg.setImageDrawable(drawable);
                                                binding.liveSvg.startAnimation();
                                            }
                                            @Override
                                            public void onError() {

                                            }
                                        });
                                    } catch (MalformedURLException e) {
                                        e.printStackTrace();
                                    }
                                }
                                break;
                            case "10":
                                LogUtils.d("钻石" + new Gson().toJson(messageEntity));
                                if(!TextUtils.isEmpty(messageEntity.getMessage())){
                                    //钻石
                                    binding.tvLiveDiamond.setText(messageEntity.getMessage());
                                }else {
                                    tvLiveViewModel.anchorView(userMobile.getUser_id());
                                }
                                return;
                        }
                        tvLiveMessageAdapter.setCustomMessage(customMessage);
                        binding.tvMessageList.post(new Runnable() {
                            @Override
                            public void run() {
                                binding.tvMessageList.scrollToPosition(tvLiveMessageAdapter.getCustomMessageList().size() - 1);
                            }
                        });
                        //获取群成员列表
                        getGroupMemberList();
                    }
                }else if(position == 2){//收到PK通知
                    byte[] customData = (byte[]) mObject;
                    if(null != customData && customData.length > 0){
                        String text = new String(customData);
                        CustomMessage customMessage = new Gson().fromJson(text,CustomMessage.class);
                        PKHomeowners pkHomeowners = new PKHomeowners();
                        pkHomeowners.setReason("主播拒绝了您的PK请求");
                        pkHomeowners.setType("response");
                        pkHomeowners.setResult("reject");
                        pkHomeowners.setUserID(customMessage.data.getUserID());
                        pkHomeowners.setAccelerateURL(customMessage.data.getAccelerateURL());
                        pkHomeowners.setTimestamp(System.currentTimeMillis() - HttpRequests.mTimeDiff);
                        cameraPush.responseRoomPK(pkHomeowners);
                    }
//                    byte[] customData = (byte[]) mObject;
//                    if(null != customData && customData.length > 0){
//                        String text = new String(customData);
//                        CustomMessage customMessage = new Gson().fromJson(text,CustomMessage.class);
//                        if(customMessage.cmd.equals("pk")){
//                            if(TextUtils.isEmpty(customMessage.data.getAction())){
//                                if(customMessage.data.getResult().equals("accept")){//收到PK同意邀请
//                                    mPKAnchorInfo.userAvatar = customMessage.data.getUserAvatar();
//                                    mPKAnchorInfo.userName = customMessage.data.getUserName();
//                                    mPKAnchorInfo.accelerateURL = customMessage.data.getAccelerateURL();
//                                    setLivePushUrl(mPKAnchorInfo.accelerateURL);
//                                }else if(customMessage.data.getResult().equals("reject")){//主播未处理请求
//                                    ToastUtils.make().show("主播未处理请求");
//                                }
//                            }else {
//                                if(customMessage.data.getAction().equals("stop")){//结束PK
//                                    //结束PK
//                                    finishPk();
//                                }else if(customMessage.data.getAction().equals("start")){
//                                    //区分是邀请还是收到
//                                    tvLiveViewModel.differentiate.set(false);
//                                    mPKAnchorInfo.userAvatar = customMessage.data.getUserAvatar();
//                                    mPKAnchorInfo.userName = customMessage.data.getUserName();
//                                    mPKAnchorInfo.userID = customMessage.data.getUserID();
//                                    mPKAnchorInfo.other_id_pk = customMessage.data.getUserID();
//                                    mPKAnchorInfo.accelerateURL = customMessage.data.getAccelerateURL();
//
//                                    if(TextUtils.isEmpty(customMessage.data.getAccelerateURL())){
//                                        //直播列表
//                                        tvLiveViewModel.livePk(mPKAnchorInfo.userID);
//                                    }else {
//                                        receivedPKMessage(mPKAnchorInfo.accelerateURL);
//                                    }
//                                }
//                            }
//                        }
//                    }
                }
            }
        });
        //
        loginIMUtils.setGroupListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                redRainDistinguish = position;
                if(position == 101 || position == 6){
                    //红包雨倒计时
                    binding.llRedRain.setVisibility(View.VISIBLE);
                    //红包雨到时间
                    //GIF提示
                    if(null == gifDrawablePrompt){
                        gifDrawablePrompt = (GifDrawable) binding.gifCountdownPrompt.getDrawable();
                        gifDrawablePrompt.setLoopCount(0);
                    }
                    //GIF倒计时
                    if(null == gifDrawable){
                        gifDrawable = (GifDrawable) binding.gifCountdown.getDrawable();
                        gifDrawable.setLoopCount(0);
                        gifDrawable.addAnimationListener(new AnimationListener() {
                            @Override
                            public void onAnimationCompleted(int i) {
                                gifDrawablePrompt.stop();
                                gifDrawable.stop();
                                binding.llRedRain.setVisibility(View.GONE);
                                //红包雨下雨
                                mRedPacketViewHelper.endGiftRain();
                                getWindow().getDecorView().postDelayed(() -> {
                                    List<BoxInfo> boxInfos = new ArrayList<>();
                                    for (int redrain = 0; redrain < 100; redrain++) {
                                        BoxInfo boxInfo = new BoxInfo();
                                        boxInfo.setAwardId(redrain);
                                        boxInfo.setVoucher("ice " + redrain);
                                        boxInfos.add(boxInfo);
                                    }
                                    mRedPacketViewHelper.launchGiftRainRocket(0, boxInfos, new RedPacketViewHelper.GiftRainListener() {
                                        @Override
                                        public void startLaunch() {

                                        }

                                        @Override
                                        public void startRain() {

                                        }

                                        @Override
                                        public void openGift(BoxPrizeBean boxPrizeBean) {

                                        }

                                        @Override
                                        public void endRain() {

                                        }
                                    });
                                }, 0);
                            }
                        });
                    }
                    //GIF提示
                    if(null != gifDrawablePrompt && !gifDrawablePrompt.isRunning()){
                        gifDrawablePrompt.start();
                    }
                    if(null != gifDrawable && !gifDrawable.isRunning()){
                        gifDrawable.start();
                    }

                }
            }
        });
        //直播列表
        tvLiveViewModel.StartLiveMobileList.observe(this, new Observer<List<StartLiveMobile>>() {
            @Override
            public void onChanged(List<StartLiveMobile> startLiveMobiles) {
                if (startLiveMobiles.size() == 2){
                    String rivalPushUrl = "";
                    if (mPKAnchorInfo.userID.equals(startLiveMobiles.get(0).getUser_id())) {
                        rivalPushUrl = startLiveMobiles.get(0).getUser_id() +"";
                    }else if (mPKAnchorInfo.userID.equals(startLiveMobiles.get(1).getUser_id() +"")) {
                        rivalPushUrl = startLiveMobiles.get(1).getPush_url();
                    }
                    mPKAnchorInfo.accelerateURL = rivalPushUrl;
                    LogUtils.d("JSON" + new Gson().toJson(mPKAnchorInfo));
                    if(tvLiveViewModel.differentiate.get()) {//邀请
                        //发送PK消息
                        sendPKMessage("邀请");
                    }else {
                        //收到邀请通知
                        receivedPKMessage(rivalPushUrl);
                    }
                }else{
                    ToastUtils.make().show("收到无效的PK请求，对方主播信息出错");
                }
            }
        });
        /**
         * PK倒计时
         */
        countDownTimerSupport.setOnCountDownTimerListener(new OnCountDownTimerListener() {
            @Override
            public void onTick(long millisUntilFinished) {

                binding.tvPkClock.setText(millisUntilFinished / 1000 +"");

            }

            @Override
            public void onFinish() {

            }
        });
        // //主播接的任务列表
        tvLiveViewModel.mSellGoodsMobileList.observe(this, new Observer<List<SellGoodsMobile>>() {
            @Override
            public void onChanged(List<SellGoodsMobile> sellGoodsMobileList) {
                if(null != sellGoodsMobileList && sellGoodsMobileList.size() > 0){
                    for (SellGoodsMobile sellGoodsMobile : sellGoodsMobileList){
                        if(sellGoodsMobile.getS_status() == 1){
                            //发送开始带货
                            loginIMUtils.sendSellGoods(sellGoodsMobile, tvLiveViewModel.liveMessageMobileMutableLiveData.getValue().getRoom_id());
                        }
                    }

                    sellGoodsAdapter.setSellGoodsMobile(sellGoodsMobileList);
                }
            }
        });

    }

    /**
     * 发送PK消息
     */
    public void sendPKMessage(String differentiate){
        PKHomeowners pkHomeowners = new PKHomeowners();
        pkHomeowners.setType("request");
        if(differentiate.equals("结束")){
            pkHomeowners.setAction("stop");
            //结束PK
            finishPk();
        }else if(differentiate.equals("邀请")){
            pkHomeowners.setAction("start");
        }
        pkHomeowners.setUserID(userMobile.getUser_id());
        pkHomeowners.setUserAvatar(userMobile.getHead_portrait());
        pkHomeowners.setUserName(userMobile.getNickname());
        pkHomeowners.setRoomID(tvLiveViewModel.startLiveMobileObservableField.get().getRoom_id());
        LogUtils.d(mPKAnchorInfo.userID);
        pkHomeowners.setOn_user_id(mPKAnchorInfo.userID);//发送到那个用户的ID
        pkHomeowners.setTimestamp(System.currentTimeMillis() - HttpRequests.mTimeDiff);
        LogUtils.d("发送邀请或者结束" + new Gson().toJson(pkHomeowners));
        cameraPush.requestRoomPK(pkHomeowners);
    }

    /**
     * 收到邀请通知
     * @param rivalPushUrl
     */
    public void receivedPKMessage(String rivalPushUrl){
        if(null != livePromptDialog && !livePromptDialog.isShowing()){
            livePromptDialog.show();
            livePromptDialog.setTitle(mPKAnchorInfo.userName + "向您发起PK请求");
            livePromptDialog.setShut("拒绝");
            livePromptDialog.setConfirm("接受");
            PKHomeowners pkHomeowners = new PKHomeowners();
            livePromptDialog.setAddItemOnClickListener(new AddItemOnClickListener() {
                @Override
                public void onSkipClicked(int position, Object mObject) {
                    livePromptDialog.dismiss();
                    if(position == 0) {//拒绝
                        pkHomeowners.setReason("主播拒绝了您的PK请求");
                        pkHomeowners.setType("response");
                        pkHomeowners.setResult("reject");
                        pkHomeowners.setUserID(mPKAnchorInfo.userID);
                        pkHomeowners.setAccelerateURL(mPKAnchorInfo.accelerateURL);
                        pkHomeowners.setTimestamp(System.currentTimeMillis() - HttpRequests.mTimeDiff);
                        cameraPush.responseRoomPK(pkHomeowners);
                    }else if(position == 1) {//接受
                        pkHomeowners.setReason("主播接受了您的连麦请求，开始连麦");
                        pkHomeowners.setType("response");
                        pkHomeowners.setResult("accept");
                        pkHomeowners.setUserID(mPKAnchorInfo.userID);
                        pkHomeowners.setRoomID(tvLiveViewModel.startLiveMobileObservableField.get().getRoom_id());
                        pkHomeowners.setAccelerateURL(tvLiveViewModel.startLiveMobileObservableField.get().getPush_url());
                        pkHomeowners.setTimestamp(System.currentTimeMillis() - HttpRequests.mTimeDiff);
                        pkStartTime = TimeUtils.getPkTime();
                        mPKAnchorInfo.start_time_pk = pkStartTime;
                        cameraPush.responseRoomPK(pkHomeowners);
                        setLivePushUrl(rivalPushUrl);
                    }
                }
            });
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.img_live_message://发送消息
                if(null != liveSendMessageDialog && !liveSendMessageDialog.isShowing()) {
                    liveSendMessageDialog.show();
                    liveSendMessageDialog.setAddOnClickListener(new AddOnClickListener() {
                        @Override
                        public void onSkipClicked(String sKip) {
                            sendMessage(sKip);
                            liveSendMessageDialog.dismiss();
                        }
                    });
                }
                break;
            case R.id.img_live_shrinkage://直播收缩
                if(null != liveShrinkageDialog && !liveShrinkageDialog.isShowing()){
                    liveShrinkageDialog.show();
                    liveShrinkageDialog.playState(pauseLive,isPk);
                    liveShrinkageDialog.setAddItemOnClickListener(new AddItemOnClickListener() {
                        @Override
                        public void onSkipClicked(int position, Object mObject) {
                            ShrinkageMobile shrinkageMobile = (ShrinkageMobile) mObject;
                            if(null != shrinkageMobile){
                                if(shrinkageMobile.getName().equals("美颜")){
                                    liveShrinkageDialog.dismiss();
                                    binding.faceUnityView.setVisibility(View.VISIBLE);
                                }else if(shrinkageMobile.getName().equals("切换相机")){
                                    mFrontCameraFlag = !mFrontCameraFlag;
                                    liveShrinkageDialog.dismiss();
                                    cameraPush.switchCamera();
                                }else if(shrinkageMobile.getName().equals("闪光灯")){
                                    liveShrinkageDialog.dismiss();
                                    mIsTorchOpenFlag = !mIsTorchOpenFlag;
                                    if(mFrontCameraFlag){
                                        ToastUtils.make().show("前置摄像头不能开启闪光灯");
                                        return;
                                    }
                                    cameraPush.getTXLivePusher().turnOnFlashLight(mIsTorchOpenFlag);
                                }else if(shrinkageMobile.getName().equals("音乐")){
                                    liveShrinkageDialog.dismiss();
                                    binding.liveMusicMixer.setVisibility(View.VISIBLE);
                                }else if(shrinkageMobile.getName().equals("结束pk")){//结束Pk
                                    liveShrinkageDialog.dismiss();
                                    ////结束Pk
                                    sendPKMessage("结束");
                                }else if(shrinkageMobile.getName().equals("pk")){//弹框PK
                                    //获取直播列表
                                    cameraPush.getPKHttpRequests().getRoomList(new PKHttpRequests.OnResponseCallback<HttpResponse.RoomList>() {
                                        @Override
                                        public void onResponse(int retcode, @Nullable @org.jetbrains.annotations.Nullable String retmsg, @Nullable @org.jetbrains.annotations.Nullable HttpResponse.RoomList data) {
                                            if (retcode != HttpResponse.CODE_OK  || data == null || data.rooms == null){
                                                LogUtils.d(retcode + "获取直播列表失败" + retmsg );
                                            }else {
                                                final List<AnchorInfo> anchorInfoList = new ArrayList<>();
                                                for (RoomInfo roomInfo : data.rooms){
                                                    AnchorInfo pusherInfo = roomInfo.pushers.get(0);
                                                    if(!pusherInfo.userID.equals(userMobile.getUser_id())){
                                                        anchorInfoList.add(pusherInfo);
                                                    }
                                                }
                                                if(anchorInfoList.size() > 0){
                                                    liveShrinkageDialog.dismiss();
                                                    LogUtils.d(new Gson().toJson(anchorInfoList));
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            if(null != onlineDialog && !onlineDialog.isShowing()){
                                                                onlineDialog.show();
                                                                onlineDialog.setAdd(anchorInfoList);
                                                                onlineDialog.setAddItemOnClickListener(new AddItemOnClickListener() {
                                                                    @Override
                                                                    public void onSkipClicked(int position, Object mObject) {
                                                                        AnchorInfo anchorInfo = (AnchorInfo) mObject;
                                                                        if(null != anchorInfo){
                                                                            onlineDialog.dismiss();
                                                                            //区分是邀请还是收到
                                                                            tvLiveViewModel.differentiate.set(true);
                                                                            mPKAnchorInfo.userID = anchorInfo.userID;
                                                                            mPKAnchorInfo.userName = anchorInfo.userName;
                                                                            mPKAnchorInfo.userAvatar = anchorInfo.userAvatar;
                                                                            //直播列表
                                                                            tvLiveViewModel.livePk(anchorInfo.userID);
                                                                        }
                                                                    }
                                                                });
                                                            }else {
                                                                ToastUtils.make().show("显示中");
                                                            }
                                                        }
                                                    });
                                                }else {
                                                    ToastUtils.make().show("暂无主播");
                                                }

                                            }

                                        }
                                    });
                                }else if(shrinkageMobile.getName().equals("观众镜像")){
                                    audienceMirroring = !audienceMirroring;
                                    //设置开启或关闭观众端镜像
                                    cameraPush.setMirror(audienceMirroring);
                                    if(audienceMirroring){
                                        cameraPush.setLocalVideoMirrorType(TXLiveConstants.LOCAL_VIDEO_MIRROR_TYPE_ENABLE);
                                    }else {
                                        cameraPush.setLocalVideoMirrorType(TXLiveConstants.LOCAL_VIDEO_MIRROR_TYPE_DISABLE);
                                    }
                                }else if(shrinkageMobile.getName().equals("继续直播")){
                                    pauseLive = true;
                                    //恢复播放
                                    cameraPush.resume();
                                    binding.imgLeave.setVisibility(View.GONE);
                                    liveShrinkageDialog.dismiss();
                                }else if(shrinkageMobile.getName().equals("暂停直播")){
                                    pauseLive = false;
                                    //暂停播放。
                                    cameraPush.pause();
                                    binding.imgLeave.setVisibility(View.VISIBLE);
                                    liveShrinkageDialog.dismiss();
                                }
                            }
                        }
                    });
                }
                break;
            case R.id.ll_tv_even_mai://连麦点击

                break;
            case R.id.img_live_occlude://关闭
                if(null != liveOccludeDialog && !liveOccludeDialog.isShowing()){
                    liveOccludeDialog.show();
                    liveOccludeDialog.setAddItemOnClickListener(new AddItemOnClickListener() {
                        @Override
                        public void onSkipClicked(int position, Object mObject) {
                            loginIMUtils.dismissGroup(startLiveMobile.getRoom_id(), new V2TIMCallback() {
                                @Override
                                public void onSuccess() {
                                    liveOccludeDialog.dismiss();
                                    cameraPush.stopPush();
                                    //退出登录
                                    HttpRequests.getInstance().logout();
                                    //关闭
                                    finish();
                                }

                                @Override
                                public void onError(int code, String desc) {
                                    LogUtils.d(code + "失败" + desc);
                                }
                            });

                        }
                    });
                }
                break;
        }
    }


    @Override
    public void onPushStart(int code) {

    }

    @Override
    public void onPushResume() {

    }

    @Override
    public void onPushPause() {

    }

    @Override
    public void onPushStop() {

    }

    @Override
    public void onSnapshot(File file) {

    }

    @Override
    public void onPushEvent(int event, Bundle param) {

    }

    @Override
    public void onNetStatus(Bundle status) {

    }

    @Override
    public void onActivityRotationObserverChange(boolean selfChange) {

    }


    //
    private long currentTime;
    private void setVideoProcessListener(TXLivePusher livePusher){
        if (mFURenderer == null) {
            return;
        }
        livePusher.setVideoProcessListener(new TXLivePusher.VideoCustomProcessListener() {
            private boolean mIsFirstFrame = true;

            /**
             * 在OpenGL线程中回调，在这里可以进行采集图像的二次处理
             * @param i  纹理ID
             * @param i1      纹理的宽度
             * @param i2     纹理的高度
             * @return 返回给SDK的纹理
             * 说明：SDK回调出来的纹理类型是GLES20.GL_TEXTURE_2D，接口返回给SDK的纹理类型也必须是GLES20.GL_TEXTURE_2D
             */
            @Override
            public int onTextureCustomProcess(int i, int i1, int i2) {
                if (mIsFirstFrame) {
                    mFURenderer.onSurfaceCreated();
                    mIsFirstFrame = false;
                    return 0;
                }
                //三星s6总是会出现花屏
                if (System.currentTimeMillis() - currentTime < 200){
                    mFURenderer.onDrawFrameSingleInput(i, i1, i2);
                }
                long start = System.nanoTime();
                int texId = mFURenderer.onDrawFrameSingleInput(i, i1, i2);
                long renderTime = System.nanoTime() - start;
                return texId;
            }

            /**
             * 增值版回调人脸坐标
             * @param floats   归一化人脸坐标，每两个值表示某点P的X,Y值。值域[0.f, 1.f]
             */
            @Override
            public void onDetectFacePoints(float[] floats) {

            }

            /**
             * 在OpenGL线程中回调，可以在这里释放创建的OpenGL资源
             */
            @Override
            public void onTextureDestoryed() {
                mFURenderer.onSurfaceDestroyed();
                mIsFirstFrame = true;
            }
        });
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        if (Math.abs(x) > 3 || Math.abs(y) > 3) {
            if (Math.abs(x) > Math.abs(y)) {
                mFURenderer.onDeviceOrientationChanged(x > 0 ? 270 : 90);
            } else {
                mFURenderer.onDeviceOrientationChanged(y > 0 ? 0 : 180);
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    //获取群成员列表
    private void getGroupMemberList(){
        // 获取群成员列表
        loginIMUtils.getGroupMemberList(startLiveMobile.getRoom_id(), new V2TIMValueCallback<V2TIMGroupMemberInfoResult>() {
            @Override
            public void onSuccess(V2TIMGroupMemberInfoResult v2TIMGroupMemberInfoResult) {
                liveStudioNumber = liveStudioNumber + v2TIMGroupMemberInfoResult.getMemberInfoList().size();
                tvLiveViewModel.number.set(liveStudioNumber);
                binding.tvLiveNumber.setText(liveStudioNumber +"");
                //更新直播间人数
                tvLiveViewModel.realLiveUpdate();
            }

            @Override
            public void onError(int code, String desc) {

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mDanmuMgr != null) {
            mDanmuMgr.resume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mDanmuMgr != null) {
            mDanmuMgr.pause();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //结束推流
        cameraPush.stopPush();

        if (mDanmuMgr != null) {
            mDanmuMgr.destroy();
            mDanmuMgr = null;
        }
    }

    /**
     * 显示Pk直播
     * @param push_url
     */
    public void setLivePushUrl(String push_url){
        LogUtils.d("push_url" + push_url);
        if(!TextUtils.isEmpty(push_url)){
            //重置并启动倒计时
            countDownTimerSupport.reset();
            countDownTimerSupport.start();
            //PK时间
            binding.tvPkClock.setVisibility(View.VISIBLE);
            //pk直播画面
            binding.pkRightVideo.setVisibility(View.VISIBLE);
            //界面转换成16比9的双小屏
            FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) binding.llPkRxCVV.getLayoutParams();
            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf((new BigDecimal(binding.llPkRxCVV.getMeasuredWidth())).divide(new BigDecimal(18))));
            BigDecimal height = new BigDecimal(String.valueOf(bigDecimal1.multiply(new BigDecimal(16))));
            LogUtils.d("height" + height);
            layoutParams1.height = Integer.parseInt(String.valueOf(height));
            binding.llPkRxCVV.setLayoutParams(layoutParams1);
            player = new TXLivePlayer(mContext);
            player.enableHardwareDecode(true);
            player.setPlayerView(binding.pkRightVideo);
            player.setRenderMode(TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN);
            player.setPlayListener(new ITXLivePlayListener() {
                @Override
                public void onPlayEvent(final int event, final Bundle param) {
                    if(event == TXLiveConstants.PLAY_ERR_NET_DISCONNECT || event == TXLiveConstants.PLAY_ERR_GET_RTMP_ACC_URL_FAIL){
                        //结束Pk
                        finishPk();
                    }
                }
                @Override
                public void onNetStatus(Bundle bundle) {

                }
            });
            int result = player.startPlay(push_url, TXLivePlayer.PLAY_TYPE_LIVE_RTMP_ACC);
            if (result != 0) {
                LogUtils.d("播放成员地址失败" );
            }else {
                //当前是否在pk中
                isPk = true;
                pkStartTime = TimeUtils.getPkTime();
                AnchorInfopk anchorInfopk = new AnchorInfopk();
                anchorInfopk.other_id_pk = mPKAnchorInfo.userID;
                anchorInfopk.accelerateURL = mPKAnchorInfo.accelerateURL;
                anchorInfopk.start_time_pk = pkStartTime;

                MessageEntity PkmessageEntity = new MessageEntity();
                PkmessageEntity.setMessage(new Gson().toJson(anchorInfopk));
                PkmessageEntity.setNickname(MerchantSession.getInstance().getUser().getNickname());
                PkmessageEntity.setRank(MerchantSession.getInstance().getUser().getLevel());
                PkmessageEntity.setLevel_img(MerchantSession.getInstance().getUser().getLevel_img());
                PkmessageEntity.setIs_guard("0");
                //发送群PK消息
                PksendGroup(String.valueOf(TCConstants.IMCMD_enter_pk),new Gson().toJson(PkmessageEntity));
                //向刚进入房间的观众更新对方主播的礼物进度条
                PksendGroup(String.valueOf(TCConstants.IMCMD_pk_gift_progress), new Gson().toJson(pkProgress));
                //向刚进入房间的观众更新PK贡献表
                MessageEntity pKmessageEntity = new MessageEntity();
                pKmessageEntity.setMessage(new Gson().toJson(pkContributionList));
                PksendGroup(String.valueOf(TCConstants.IMCMD_pk_contributionList), new Gson().toJson(pKmessageEntity));
            }

        }
    }

    /**
     * 结束Pk
     */
    public void finishPk(){
        //PK时间
        binding.tvPkClock.setVisibility(View.GONE);
        //
        binding.pkRightVideo.setVisibility(View.GONE);
        FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) binding.llPkRxCVV.getLayoutParams();
        layoutParams1.height = ViewGroup.LayoutParams.MATCH_PARENT;
        binding.llPkRxCVV.setLayoutParams(layoutParams1);
        //停止播放。
        player.stopPlay(true);
        //当前是否在pk中
        isPk = false;
        //停止倒计时
        countDownTimerSupport.stop();
    }

    /**
     * 发送群PK消息
     */
    public void PksendGroup(String cmd,String json){
        loginIMUtils.sendGroupCustomMessage(cmd, json, startLiveMobile.getRoom_id(), new V2TIMValueCallback<V2TIMMessage>() {
            @Override
            public void onSuccess(V2TIMMessage v2TIMMessage) {
                LogUtils.d("发送成功");
            }

            @Override
            public void onError(int code, String desc) {

            }
        });
    }









    /**
     * 发送消息
     * @param sKip
     */
    public void sendMessage(String sKip){
        //弹幕
        if(liveSendMessageDialog.play){
            if (mDanmuMgr != null) {
                mDanmuMgr.addDanmu(userMobile.getHead_portrait(), userMobile.getNickname(), sKip);
            }
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setMessage(sKip);
            messageEntity.setNickname(MerchantSession.getInstance().getUser().getNickname());
            messageEntity.setRank(MerchantSession.getInstance().getUser().getLevel());
            messageEntity.setLevel_img(MerchantSession.getInstance().getUser().getLevel_img());
            messageEntity.setType("white");
            messageEntity.setIs_guard("");
            //发生自定义消息
            loginIMUtils.sendGroupCustomMessage("5", new Gson().toJson(messageEntity), startLiveMobile.getRoom_id(), new V2TIMValueCallback<V2TIMMessage>() {
                @Override
                public void onSuccess(V2TIMMessage v2TIMMessage) {
                    LogUtils.d("成功");
                    //添加消息
                    CustomMessage customMessage = new CustomMessage();
                    customMessage.cmd = "5";
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setRank(Integer.valueOf(userMobile.getLevel()));
                    messageEntity.setNickname(userMobile.getNickname());
                    messageEntity.setLevel_img(userMobile.getLevel_img());
                    messageEntity.setMessage(sKip);
                    customMessage.msg = new Gson().toJson(messageEntity);
                    if(null != customMessage){
                        tvLiveMessageAdapter.setCustomMessage(customMessage);
                        binding.tvMessageList.post(new Runnable() {
                            @Override
                            public void run() {
                                binding.tvMessageList.scrollToPosition(tvLiveMessageAdapter.getCustomMessageList().size() - 1);
                            }
                        });
                    }
                }

                @Override
                public void onError(int code, String desc) {
                    LogUtils.d(code + "发送失败" + desc);
                }
            });
        }else {
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setMessage(sKip);
            messageEntity.setNickname(MerchantSession.getInstance().getUser().getNickname());
            messageEntity.setRank(MerchantSession.getInstance().getUser().getLevel());
            messageEntity.setLevel_img(MerchantSession.getInstance().getUser().getLevel_img());
            messageEntity.setType("white");
            messageEntity.setIs_guard("");
            //发生自定义消息
            loginIMUtils.sendGroupCustomMessage("1", new Gson().toJson(messageEntity), startLiveMobile.getRoom_id(), new V2TIMValueCallback<V2TIMMessage>() {
                @Override
                public void onSuccess(V2TIMMessage v2TIMMessage) {
                    LogUtils.d("成功");
                    //添加消息
                    CustomMessage customMessage = new CustomMessage();
                    customMessage.cmd = "1";
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setRank(Integer.valueOf(userMobile.getLevel()));
                    messageEntity.setNickname(userMobile.getNickname());
                    messageEntity.setLevel_img(userMobile.getLevel_img());
                    messageEntity.setMessage(sKip);
                    customMessage.msg = new Gson().toJson(messageEntity);
                    if(null != customMessage){
                        tvLiveMessageAdapter.setCustomMessage(customMessage);
                        binding.tvMessageList.post(new Runnable() {
                            @Override
                            public void run() {
                                binding.tvMessageList.scrollToPosition(tvLiveMessageAdapter.getCustomMessageList().size() - 1);
                            }
                        });
                    }
                }

                @Override
                public void onError(int code, String desc) {
                    LogUtils.d(code + "发送失败" + desc);
                }
            });
        }
    }
}
